package cn.xyt.util;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpMethod;
import org.springframework.http.client.AsyncClientHttpRequest;

import cn.tom.db.jdbc.Query;
import cn.tom.db.jdbc.simple.DBQuery;
import cn.tom.db.jdbc.simple.DBUtil;
import cn.tom.kit.StringUtil;
import cn.tom.protocol.http.HttpMessage;
import sun.misc.BASE64Encoder;

/**
 * 	推送 消息分三块
	1. 电池信息, 充电, 电量
	2. 震动报警
 * 	@author tomsun	
 */
public class JPushUtil {
	private static final String appkey = "e72496fa54e5adfed5d65884";
	private static final String masterSecret = "ba352a518f014cf8351c8bcc";
	private static final String auth =new  BASE64Encoder().encode((appkey+":"+masterSecret).getBytes());//base64(appKey:masterSecret)
	
	/**
	 * 推送所有设备
	 * @param alert
	 * @return
	 * @throws Exception
	 */
	public static String pushAll(String alert) throws Exception {
		AsyncClientHttpRequest request = HttpUtil.createRequest("https://api.jpush.cn/v3/push", HttpMethod.POST);
		request.getHeaders().set("Authorization", "Basic " + auth);
		request.getHeaders().set("Content-Type", "application/json");
		//'options':{'apns_production':false},  //TODO 去掉修改正式环境, 或改true
		byte content[] = ("{'platform':'all','audience':'all','notification':{'alert':'" + alert + "'}}").replace('\'', '"').getBytes("UTF-8");
		request.getBody().write(content);
		return HttpUtil.exec(request);
	}
	
	/**
	 * 推送指定注册设备
	 * @param alert
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public static String pushByid(String alert,String sound, String[] id ) throws Exception{
		AsyncClientHttpRequest request = HttpUtil.createRequest("https://api.jpush.cn/v3/push", HttpMethod.POST);
		request.getHeaders().set("Authorization", "Basic " + auth);
		request.getHeaders().set("Content-Type", "application/json");
		String ids = StringUtil.join(id, ",");
		sound = StringUtil.isEmpty(sound) ? "default" : sound;
		//'options':{'apns_production':false}, 'ios' : {'sound': 'default'}  //TODO 去掉修改正式环境, 或改true IOS需要加默认推送音 
		String pcontent ="{'options':{'apns_production':true},'platform':'all','audience':{'alias':["+ids+"]},"
						+ "'message':{'msg_content':'"+alert+"','extras': {'sound': '"+sound+"'}}," //自定义消息
						+ "'notification':{'ios' : {'alert':'"+alert+"', 'sound': '"+sound+"'}}}"; //通知,IOS 专用
		byte content [] = pcontent.replace('\'', '"').getBytes("UTF-8");
		request.getBody().write(content);
		HttpUtil.logger.info(request.getURI()+"::"+new String(content));
		return HttpUtil.exec(request);
	}
	

	/**
	 * @param alert
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public static String checkPush(String alert, int uid) throws Exception{
		Map<String, Object> map = DBUtil.getMap("select push_mode,push_voice from deviceset where uid =?", uid);
		if((int)map.get("push_mode")==1) return "push_mode==1 不推送";
		return pushByid(alert, (String)map.get("push_voice"),  new String[]{ "'"+uid+"'"});
	}
	
	
	
	/**
	 * //TODO 警告推送
	 * @param state
	 * @param uid
	 */
	public static void pushWarn(String state, int deviceid){
		String msg = "车辆已恢复正常，请不用担心车辆安全";
	
		char s = state.charAt(7);
		if(s=='1') msg = "车辆震动报警，请检查车辆周边环境";
		
		s = state.charAt(6);
		if(s=='1') msg = "车辆轮动报警，请检查车辆是否被移动";
		
		s = state.charAt(5);
		if(s=='1') msg = "车辆未撤防打开钥匙，请确定是否本人操作";
		
		try {
			/*int uid = getUid(deviceid);
			if(uid == 0) {
				serverToClientPush(msg, deviceid);  // 取消车辆报警
			}else{
				//JPushUtil.checkPush(msg, getUid(deviceid));// 取消车辆报警
				DBUtil.exec("insert into pushinfo(uid, title, content) values(?,?,?)", uid, "车辆报警信息", msg);
			}*/
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public static void pushBattery(String state, String state1, int deviceid, double chargetime){
		int charge_errcnt = 0;  //充电异常
		int use_errcnt = 0;   //使用异常
		int over_elec_cnt = 0; //过流保护
		int over_volt_cnt = 0; // 过载保护
		String msg = null;
		char c = state.charAt(7);
		if(c =='1') {
			msg = "充电未充满断开，充电时长"+String.format("%.1f",chargetime)+"小时";
			charge_errcnt++;
		}
		
		c = state.charAt(0);
		if(c =='1') {
			msg = "使用电压过压，请检查电池状态";
			use_errcnt++;
		}
		
		c = state1.charAt(7);
		if(c =='1') {
			msg = "充电量已满，已进入过载保护，请检查充电器";
			over_volt_cnt++;
		}
		
		c = state1.charAt(6);
		if(c =='1') {
			msg = "车辆电流检测故障，请检查车辆";
			use_errcnt++;
		}
		
		String s = state.substring(1, 3);
		if("01".equals(s)) {
			msg = "充电电流过流，请检查充电器";
			over_elec_cnt++;
		}
		if("10".equals(s)) {
			msg = "报警电流过流，请检查充电器";
			over_elec_cnt++;
		}
		
		s = state.substring(5, 7);
		if("01".equals(s)) {
			msg = "使用电池欠压，请及时充电";
			use_errcnt++;
		}
		if("10".equals(s)) {
			msg = "使用电压过压，请检查电池";
			use_errcnt++;
		}
		if("11".equals(s)) {
			msg = "车辆电池被移除，请确定是否本人操作，谨防被盗";
			use_errcnt++;
		}
		
		try {
			if(msg ==null) return;
			int uid = getUid(deviceid);
			if("11".equals(s)) {   // 只做电池被移除推送
				if(uid == 0) { 
					//TODO 电池被移除 反向推送到 租车api
					pushWarninfo(msg, deviceid); // 推送到 租车api
				}else{
					DBUtil.exec("insert into pushinfo(uid, title, content) values(?,?,?)", uid, "电池报警信息", msg);
					JPushUtil.checkPush(msg, uid);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		parseLife(deviceid, charge_errcnt, use_errcnt, over_elec_cnt, over_volt_cnt, 0);
	}
	
	/**
	 * 增加寿命的计算
	 * @param charge_errcnt
	 * @param use_errcnt
	 * @param over_elec_cnt
	 * @param over_volt_cnt
	 * @param charge_cnt
	 */
	public static void parseLife(int deviceid, int charge_errcnt, int use_errcnt, int over_elec_cnt, int over_volt_cnt, int charge_cnt) {
		StringBuffer sql = new StringBuffer("update life set did=?");
		Query query = new DBQuery(sql).setParams(deviceid);
		if(charge_errcnt>0) query.add(",charge_errcnt=charge_errcnt+?").setParams(charge_errcnt); 
		if(use_errcnt>0) 	query.add(",use_errcnt=use_errcnt+?").setParams(use_errcnt); 
		if(over_elec_cnt>0) query.add(",over_elec_cnt=over_elec_cnt+?").setParams(over_elec_cnt); 
		if(over_volt_cnt>0) query.add(",over_volt_cnt=over_volt_cnt+?").setParams(over_volt_cnt); 
		if(charge_cnt>0) query.add(",charge_cnt=charge_cnt+?").setParams(charge_cnt); 
		if(query.getParams().length>1){
			query.add(" where did =?").setParams(deviceid);
			DBUtil.exec(query);
		}
	}

	
	public static int getUid(int deviceid){
		int uid = DBUtil.getInt("select uid from deviceset where deviceid = ?", deviceid);
		return uid;
	}
	
	public static Map<String, PullSession>  pullMap = new HashMap<>();
	
	/**
	 * 推送车辆报警
	 * @param pushMsg
	 * @param deviceid
	 */
	public static void pushWarninfo(String pushMsg, int deviceid){
		PullSession session = pullMap.get("pushMsg");  //topic
		if(session == null) return;
		HttpMessage msg = session.getPullMessage();
		msg.setCommand("pushMsg");
		msg.setHead("type", "warninfo");
		String body = deviceid +"^"+ pushMsg;
		msg.setBody(body);
		session.getSession().write(msg);
	}
	
	/**
	 * 推送gps经纬度
	 * @param deviceid
	 * @param lat_lng
	 */
	public static void pushGps(int deviceid, double lat, double lng){
		PullSession session = pullMap.get("pushMsg"); //topic
		if(session == null) return;
		HttpMessage msg = new HttpMessage();
		msg.setCommand("pushMsg");
		msg.setHead("type", "gps");
		msg.setHead("deviceid", ""+deviceid);
		msg.setHead("lat",Double.toString(lat) );
		msg.setHead("lng",Double.toString(lng));
		msg.setBody(new byte[]{});
		session.getSession().write(msg);
	}
	
	
	/**
	 * 
	 * @param deviceid
	 * @param boolean start = "1".equals(msg.getParam("start"));
	 * 1 启动 0 关闭
	 * 推送启动关闭标记, 记录车辆 分段轨迹
	 */
	public static void pushMove(int deviceid, int start){
		PullSession session = pullMap.get("pushMsg"); //topic
		if(session == null) return;
		HttpMessage msg = new HttpMessage();
		msg.setCommand("pushMsg");
		msg.setHead("type", "move");
		msg.setHead("deviceid", ""+deviceid);
		msg.setHead("start", ""+start);
		msg.setBody(new byte[]{});
		session.getSession().write(msg);
	}
	
	/**
	 * 推送低电量
	 * @param deviceid
	 * @param last
	 */
	public static void pushVoltLow(int deviceid, double last){
		PullSession session = pullMap.get("pushMsg"); //topic
		if(session == null) return;
		HttpMessage msg = new HttpMessage();
		msg.setCommand("pushMsg");
		msg.setHead("type", "voltLow");
		msg.setHead("deviceid", ""+deviceid);
		msg.setHead("last", ""+last);
		msg.setBody("");
		session.getSession().write(msg);
	}
	
	/**
	 * 推送 登录状态
	 * @param deviceid
	 */
	public static void pushLoginState(int deviceid){
		String sql = "select substr(switch1,6,1)::int  from deviceone where did = ?";
		int state =  DBUtil.getInt(sql, deviceid);
		if(state == 0) return;
		
		PullSession session = pullMap.get("pushMsg"); //topic
		if(session == null) return;
		HttpMessage msg = new HttpMessage();
		msg.setCommand("pushMsg");
		msg.setHead("type", "loginState");
		msg.setHead("deviceid", ""+deviceid);
		msg.setBody("");
		session.getSession().write(msg);
	}
	
	
	public static void main(String[] args) throws Exception {
//		System.out.println(pushAll("helloall"));;
//		System.out.println(pushByid("hello by 5555", "'5'"));
//		System.out.println(pushByid("hello by 666666", "'6'"));
		
	}

}
